#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
最小化ASR服务使用示例

演示如何使用MinimalASR进行语音识别
"""

from services.asr_service import MinimalASR


def main():
    """主函数 - 演示ASR服务的基本用法"""
    
    print(" 最小化ASR服务使用示例")
    print("=" * 50)
    
    # 1. 初始化ASR服务
    print("\n1. 初始化ASR服务...")
    asr = MinimalASR(
        # 可以在这里传入自定义的API凭证
        # app_id="your_app_id",
        # access_token="your_access_token",
        cache_dir="./example_cache"
    )
    
    # 2. 准备测试音频URL
    # 注意：这里需要替换为实际可访问的音频URL
    audio_url = "https://example.com/test-audio.wav"
    
    print(f"\n2. 准备识别音频:")
    print(f"    URL: {audio_url}")
    print("    注意：请替换为实际的音频URL")
    
    # 3. 进行语音识别
    print(f"\n3. 开始语音识别...")
    
    # 由于示例URL不存在，这里会失败，但演示了正确的调用方式
    segments = asr.recognize(
        audio_url=audio_url,
        identifier="example_audio",  # 用于缓存的标识符
        use_cache=True
    )
    
    # 4. 处理识别结果
    if segments:
        print(f"\n4. 识别成功! 共 {len(segments)} 个语音段:")
        print("-" * 40)
        
        # 显示每个语音段
        for i, segment in enumerate(segments, 1):
            start_time = segment['start']
            end_time = segment['end']
            text = segment['text']
            word_count = len(segment.get('words', []))
            
            print(f"  {i:2d}. [{start_time:6.2f}s - {end_time:6.2f}s] {text}")
            print(f"      词数: {word_count}")
        
        print("-" * 40)
        
        # 获取完整文本
        full_text = asr.get_full_text(segments)
        print(f"\n 完整文本:")
        print(f"    {full_text}")
        
        # 获取词级时间戳信息
        words = asr.get_words_with_timestamps(segments)
        print(f"\n🔤 词级统计:")
        print(f"    总词数: {len(words)}")
        
        if words:
            print(f"    前5个词:")
            for i, word in enumerate(words[:5], 1):
                print(f"      {i}. [{word['start_time']:.2f}s-{word['end_time']:.2f}s] "
                      f"'{word['text']}' (置信度: {word['confidence']:.2f})")
        
        # 演示缓存功能
        print(f"\n💾 缓存演示:")
        print("    第二次调用将使用缓存...")
        segments_cached = asr.recognize(audio_url, identifier="example_audio")
        print(f"    缓存结果段数: {len(segments_cached)}")
        
    else:
        print(f"\n 识别失败或无结果")
        print("    可能的原因:")
        print("    - 音频URL无效或无法访问")
        print("    - API凭证无效")
        print("    - 网络连接问题")
        print("    - 音频格式不支持")
    
    # 5. 演示其他功能
    print(f"\n5. 其他功能演示:")
    
    # 缓存管理
    print("    缓存管理:")
    print("    - 禁用缓存")
    asr.disable_cache()
    
    print("    - 启用缓存")
    asr.enable_cache_func()
    
    print("    - 清空缓存")
    asr.clear_cache()
    
    print(f"\n 示例完成!")


def demo_with_mock_data():
    """使用模拟数据演示结果处理"""
    
    print(f"\n 模拟数据演示:")
    print("=" * 30)
    
    # 创建模拟的识别结果
    mock_segments = [
        {
            "start": 0.5,
            "end": 2.3,
            "text": "欢迎使用语音识别服务",
            "words": [
                {"text": "欢迎", "start_time": 0.5, "end_time": 0.9, "confidence": 0.95},
                {"text": "使用", "start_time": 1.0, "end_time": 1.3, "confidence": 0.92},
                {"text": "语音", "start_time": 1.4, "end_time": 1.7, "confidence": 0.88},
                {"text": "识别", "start_time": 1.8, "end_time": 2.0, "confidence": 0.90},
                {"text": "服务", "start_time": 2.1, "end_time": 2.3, "confidence": 0.93}
            ]
        },
        {
            "start": 3.0,
            "end": 5.2,
            "text": "这是一个最小化的实现",
            "words": [
                {"text": "这是", "start_time": 3.0, "end_time": 3.3, "confidence": 0.96},
                {"text": "一个", "start_time": 3.4, "end_time": 3.7, "confidence": 0.94},
                {"text": "最小化", "start_time": 3.8, "end_time": 4.3, "confidence": 0.89},
                {"text": "的", "start_time": 4.4, "end_time": 4.5, "confidence": 0.85},
                {"text": "实现", "start_time": 4.6, "end_time": 5.2, "confidence": 0.91}
            ]
        }
    ]
    
    # 初始化ASR服务（用于工具方法）
    asr = MinimalASR()
    
    print(f" 模拟识别结果:")
    for i, segment in enumerate(mock_segments, 1):
        print(f"  {i}. [{segment['start']:.1f}s - {segment['end']:.1f}s] {segment['text']}")
    
    # 演示工具方法
    full_text = asr.get_full_text(mock_segments)
    print(f"\n 完整文本: {full_text}")
    
    words = asr.get_words_with_timestamps(mock_segments)
    print(f"\n🔤 词级信息 (共{len(words)}个词):")
    for word in words:
        print(f"    '{word['text']}' [{word['start_time']:.1f}s-{word['end_time']:.1f}s] "
              f"置信度: {word['confidence']:.2f}")


if __name__ == "__main__":
    try:
        # 运行主示例
        main()
        
        # 运行模拟数据演示
        demo_with_mock_data()
        
    except KeyboardInterrupt:
        print(f"\n\n 用户中断")
    except Exception as e:
        print(f"\n 运行出错: {e}")
        import traceback
        traceback.print_exc()
